package com.wh.blog.controller;

import com.wh.blog.constant.Constants;
import com.wh.blog.model.Result;
import com.wh.blog.model.UserInfo;
import com.wh.blog.service.UserService;
import com.wh.blog.utils.JwtUtils;
import com.wh.blog.utils.SecurityUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/login", produces = "application/json")
    public Result login(String userName, String password) {
        log.info("开始登陆~~~~~");
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        UserInfo userInfo = userService.selectByName(userName);
        if (userInfo == null) {
            return Result.fail("用户名错误");
        }
//        log.info("userInfo.getPassword():{}",userInfo.getPassword());
//        log.info("{}",SecurityUtil.encrypt(password));
        if (!SecurityUtil.verify(password, userInfo.getPassword())) {
            return Result.fail("密码错误");
        }
        //密码正确, 返回token,密码错误, 返回错误信息
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_USERNAME, userName);
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        String token = JwtUtils.genJwt(claim);
        log.info("UserController#login 返回结果token:{}", token);
        return Result.success(token);
    }


    @RequestMapping("/getLoginUserInfo")
    public Result<UserInfo> getLoginUserInfo(HttpServletRequest request) {
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("token:{}", token);
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            return Result.nologin();
        }
        Integer userId = JwtUtils.getIdByToken(token);
        if (userId == null) {
            return Result.fail("数据异常，请联系管理员");
        }
        UserInfo userInfo = userService.selectById(userId);
        if (userInfo == null) {
            return Result.fail("数据异常，请联系管理员");
        }
        return Result.success(userInfo);
    }
}
